package com.project.api.ym.service;

import com.alibaba.fastjson.JSONObject;
import com.project.api.common.Unit;
import com.project.api.ym.dao.AdminDao;
import com.project.api.ym.dao.RulesDao;
import com.project.api.ym.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminService {
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private RulesDao rulesDao;

    public String Login(String username,String password){
        Admin dao ;
        String find = "select id from "+ Admin.tableName +" where username = ? and password=? limit 1";
        try {
            dao = (Admin)mainJdbcTemplate.queryForObject(
                    find, new Object[] { username,password },new BeanPropertyRowMapper(Admin.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return null;
        }
        return String.valueOf(dao.getId());
    }

    /**
     * 获取用户信息
     * @param uid
     * @return
     */
    public Admin GetAdminInfo(long uid){
        Admin dao ;
        String sql = "select id,username,avatar,mobile,`name`,realname,ctime,utime,status,banner from "+Admin.tableName+" where id=? limit 1";
        try {
            dao = (Admin)mainJdbcTemplate.queryForObject(
                    sql, new Object[] { uid },new BeanPropertyRowMapper(Admin.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return null;
        }
        if ( dao != null ) {
            dao.setRoles(adminDao.Roles(dao.getId()));
            dao.setIsfull(rulesDao.IsFullAuthByRoles(dao.getRoles()));
        }
        return dao;
    }

    @Transactional(rollbackFor=Exception.class)
    public long CreateAdmin(JSONObject json, long creator, long updateby) throws Exception {
        return adminDao.AdminCreate(json,creator,updateby);
    }
    @Transactional(rollbackFor=Exception.class)
    public long UpdateAdmin(long id,JSONObject json){
        return adminDao.AdminUpdate(id,json);
    }
}
